
<template>
  <div class="myselecttree" ref="myselecttree" :title="valueTitle">
    <el-select v-if="!readonly" popper-class="my_selecttree" ref="treeSelect" :popper-append-to-body="append" filterable :filter-method="filterKey" 
      :size="size" :value="valueTitle" :clearable="clearable" @visible-change="openOrHide" :placeholder="placeholder" @clear="clearHandle">
      <el-option :value="valueTitle" :label="valueTitle">
        <ul :id="treeId" class="ztree select-tree" @click.stop=""></ul>
      </el-option>
    </el-select>
    <el-input v-else size="medium" :value="valueTitle" :placeholder="placeholder" readonly></el-input>
  </div>
</template>
<style scoped>
.myselecttree .el-select{
  width: 100%;
}
</style>
<style lang="scss">
.my_selecttree .el-select-dropdown__list .el-select-dropdown__item{
  height: auto;
  line-height: inherit;
  font-weight: normal;
  overflow: inherit;
  padding: 0 2px;
  box-sizing: border-box;
  background-color: #fff;
}
.select-tree.ztree{
  padding-left: 10px;
  *{
    font-family: inherit;
    font-size: 14px;
  }
  li span.treeIconChannel1_ico_docu,li span.button.treeIconChannel1_ico_open,li span.button.treeIconChannel1_ico_close{
    background: url(/static/image/tree-channel1.png) 0 0 no-repeat;
    background-size: contain;
    margin-right: 3px;
  }
  li span.button.treeIconChannel2_ico_docu,li span.button.treeIconChannel2_ico_open,li span.button.treeIconChannel2_ico_close{
    background: url(/static/image/tree-channel2.png) 0 0 no-repeat;
    background-size: contain;
    margin-right: 3px;
  }
  li span.button.treeIconDevice_ico_docu,li span.button.treeIconDevice_ico_open,li span.button.treeIconDevice_ico_close{
    background: url(/static/image/tree-video.png) 0 0 no-repeat;
    background-size: contain;
    margin-right: 3px;
    background-position: 0px 2px;
  }
  li .curSelectedNode{
    background-color: #fff;
    color: #666 !important;
  }
}
</style>
<script>
export default {
  name: "select-dept-car-input",
  props:{
    thekey: {//返回值取的是node的哪个字段
      type: String,
      default:()=>{ return "id" }
    },
    /* 可清空选项 */
    clearable:{
      type:Boolean,
      default:()=>{ return true }
    },
    size: "",
    readonly: {
      type: Boolean,
      default: ()=>{
        return false
      }
    },
    append: {/* 位置 */
      type: Boolean,
      default: ()=>{
        return false
      }
    },
    placeholder: {
      type: String,
      default: ()=>{
        return "请选择"
      }
    },
  },
  data() {
    return {
      treeId: 'tree-input'+this.randomStr(8),
      valueId: "",// 放置的是thekey属性的值,和value对应的属性一致
      valueTitle: "",
      setting: {
        view: {
          expandSpeed: "",
          autoCancelSelected: false,
          fontCss : {
            "color":"#606266"
          }
        },
        check: {
          enable: true,
          chkStyle:"radio",
          radioType: "all",
          autoCheckTrigger: false,
          nocheckInherit: false,
          chkDisabledInherit: false
        },
        data: {
          key: {
            name: "name",
            isParent: "isParent",
            isHidden: "isHidden"
          },
          simpleData: {
            enable: true,
            idKey: "nodeId",
            pIdKey: "parentId",
            rootPId: ""
          }
        },
        callback: {
          beforeCheck: this.zTreeBeforeCheck,
          onCheck: this.zTreeOnCheck,
        },
      },
      treeObj: null,
      treeData: [],
      theScrollTop: 0//记录上次选中时滚动的位置
    }
  },
  mounted(){
    this.initHandle();
  },
  methods: {
    initData(){
      let that = this;
      if(that.$store.state.commentData.deptCarList&&that.$store.state.commentData.deptCarList.length>0){
        that.treeData = JSON.parse(JSON.stringify(that.$store.state.commentData.deptCarList));
        let list = [];
        function loop(arr){
          for (let i = 0; i < arr.length; i++) {
            let item = JSON.parse(JSON.stringify(arr[i]));
            delete item.children;
            item.isHidden = false;
            item.checked = false;
            if(item.nodetype){
              item.nocheck = true;
            }
            list.push(item);
            if(arr[i].children&&arr[i].children.length>0){
              loop(arr[i].children);
            }
          }
        }
        loop(that.treeData);
        that.treeData = list;//是一个数组
        if(that.treeObj){
          that.treeObj.destroy();
        }
        that.treeObj = $.fn.zTree.init($("#"+that.treeId), that.setting, that.treeData);
        that.treeObj.expandAll(true);
      }else{
        setTimeout(function(){
          that.initData();
        },1500);
      }
    },
    initHandle(){
      if(!this.readonly){
        this.initData();
        this.$nextTick(()=>{
          let scrollBar = document.querySelectorAll('.myselecttree .el-scrollbar .el-scrollbar__bar');
          let boxW = $(this.$refs['myselecttree']).width();
          $('.myselecttree .el-scrollbar .el-select-dropdown__wrap').width(boxW)
          $('.myselecttree .el-scrollbar .el-select-dropdown__wrap').css("overflow","auto")
          $('.myselecttree .el-scrollbar .el-select-dropdown__wrap').css("margin","0")
          if(scrollBar){
            for(let key  in scrollBar){
              if(scrollBar[key]&&scrollBar[key].style)scrollBar[key].style.width = 0;
            }
          }
        });
      }
    },
    zTreeBeforeCheck(treeId, treeNode){
      if(!treeNode.nodetype){
        return true;
      }else{
        return false;
      }
    },
    zTreeOnCheck(event, treeId, treeNode){//点击勾选
      if(event.srcEvent){
        // console.log("wo选中的是",treeNode.name);
        let bool = treeNode.checked;
        if(!treeNode.nodetype){
          this.treeObj.checkNode(treeNode, bool, false);
        }
        this.theScrollTop = $('#'+treeNode.tId)[0].offsetTop;
        this.valueId = bool?treeNode[this.thekey]:"";
        this.valueTitle = bool?treeNode.parentName+"/"+treeNode.name:"";
        this.$emit('selectCange',treeNode,this.valueId);
      }
    },
    filterKey(val){
      let treeList = [];//符合树搜索条件的机构车辆
      if(!val){
        this.treeData.forEach((item,index)=>{
          if(index>0){
            item.open = false;
          }else{
            item.open = true;
          }
        });
        treeList = this.treeData;
      }else{//有关键字
        let groupids = [];
        for (let i = 0; i < this.treeData.length; i++) {
          if(!!this.treeData[i].nodetype&&(this.treeData[i].id.indexOf(val)>-1||this.treeData[i].name.indexOf(val)>-1)){//有机构/设备符合条件
            groupids.push(this.treeData[i].nodeId);
            treeList.push(this.treeData[i]);
          }
        }
        if(!groupids.length){//查询是否有符合条件的通道
          for (let i = 0; i < this.treeData.length; i++) {
            if(!this.treeData[i].nodetype&&(this.treeData[i].id.indexOf(val)>-1||this.treeData[i].name.indexOf(val)>-1)){//有通道符合条件
              treeList.push(this.treeData[i]);
              if(groupids.indexOf(this.treeData[i].parentId)==-1){
                groupids.push(this.treeData[i].parentId);//把直属父级记录下来
              }
            }
          }
          for (let i = 0; i < this.treeData.length; i++) {
            let d_idx = groupids.indexOf(this.treeData[i].nodeId);
            if(d_idx>-1){
              this.treeData[i].open = true;
              treeList.unshift(this.treeData[i]);
            }
          }
        }else{//有符合条件，这些设备旗下的通道要全部显示
          for (let i = 0; i < this.treeData.length; i++) {
            if(groupids.indexOf(this.treeData[i].parentId)>-1){
              treeList.push(this.treeData[i]);
            }
          }
        }
      }
      let that = this;
      that.treeObj = $.fn.zTree.init($("#"+that.treeId), that.setting, treeList);
      that.treeObj.expandAll(true);
      that.treeLoading = false;
    },
    clearHandle(){// 清除选中
      this.valueId = '';
      this.valueTitle = '';
      this.treeObj.checkAllNodes(false);
      this.filterKey("");
      this.$emit('selectCange',"",{},"");
    },
    openOrHide(bool){//下拉框出现/隐藏时触发
      if(bool){//出现
        let that = this;
        setTimeout(() => {//滚动到指定位置
          $('.myselecttree .el-scrollbar .el-select-dropdown__wrap').scrollTop(that.theScrollTop);
        }, 0);
      }else{
        this.filterKey("");
      }
    }
  },
};
</script>